package org.alex.samples.dao;

import java.util.List;

import org.alex.samples.model.ExamUserSub;
import org.alex.samples.model.Sub;
import org.hibernate.type.IntegerType;
import org.hibernate.type.StringType;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository
@Transactional
public class SubDAOImpl extends BaseHibernateDAO<Sub> implements ISubDAO {
	
	@Override
	public List<Sub> findAllSubs() {
		String hql="from Sub";
		List<Sub> esubList = this.find(hql);
		return esubList;
	}

	@Override
	public Sub getSubById(int id) {
		Sub exsitsSub = this.get(id);
		return exsitsSub;
	
	}

	@Override
	public void createSub(Sub sub) throws Exception {
		this.save(sub);
	}

	@Override
	public void editSub(Sub sub) throws Exception {
		this.update(sub);
	}

	@Override
	public void deleteSub(int id) throws Exception {
		Sub exsitsSub = this.get(id);
		if(exsitsSub!=null){
			this.delete(exsitsSub);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<String> getAllUserBySubject(Integer subjectId) {
		StringBuilder sql = new StringBuilder();
		sql.append(" select user.user_id as userId ");
		sql.append(" from exam_user_subject eus ");
		sql.append(" left join exam_subject es on eus.sub_id = es.sub_id ");
		sql.append(" left join exam_user user on user.user_id = eus.user_id");
		sql.append(" where es.sub_id = :subjectId ");
		
		return this.createSqlQuery(String.valueOf(sql))
				.addScalar("userId", StringType.INSTANCE)
				.setInteger("subjectId", subjectId)
				.list();
	}

	@Override
	public void insertSubjectUsers(List<String> insertList, Integer subjectId) {
		String sql = null;
		for(String userId : insertList){
			sql = "insert into exam_user_subject(user_id,sub_id) values(:userId , :subjectId)";
			this.createSqlQuery(sql).setString("userId", userId).setInteger("subjectId", subjectId).executeUpdate();
		}
		
	}

	@Override
	public void deleteSubjectUsers(List<String> delList, Integer subjectId) {
	    String sql = null;
	    for(String userId : delList){
	    	sql = "delete exam_user_subject from exam_user_subject where user_id = :userId and sub_id= :subjectId";
			this.createSqlQuery(sql).setString("userId", userId).setInteger("subjectId", subjectId).executeUpdate();
	    }
		
	}

	

	

}
